from rctk.app import App
from rctk.widgets import Button, Window, Panel, List, StaticText
from rctk.layouts import GridLayout

import os

class FileChooser(Window):
    def __init__(self, tk, title="Open file..", restrict=False, **kw):
        super(FileChooser, self).__init__(tk, title, **kw)
        self.restrict = restrict

    def open(self):
        super(FileChooser, self).open()
        self.build()

    def open_file(self, e):
        selection = self.files.value
        selection = selection[0] ## single vs doubleclick

        full = os.path.normpath(os.path.join(self.current, selection))
        if not self.restrict or (os.path.isdir(full) and full.startswith(self.start)):
            self.load_directory(full)

    def open_directory(self, path):
        self.start = path.rstrip('/')
        self.load_directory(path)

    def load_directory(self, path):
        last = path.split('/')[-1]
        #self.directories.append(Button(self.tk, last))
        #self.directories.layout()

        files = sorted(os.listdir(path.decode('utf-8')))
        self.files.clear()
        self.current = path
        ## breakout protection
        if not self.restrict or (path.strip('/') != self.start.strip('/')):
            self.files.add('..', '..')

        for file in files:
            if file[0] != u'.': # optional, other checks
                file = file.encode('utf-8')
                self.files.add(file, file)

    def build(self):
        self.setLayout(GridLayout(columns=2))

        self.files = List(self.tk, multiple=True, size=20, width=400)
        self.files.doubleclick = self.open_file

        self.append(self.files, colspan=2, sticky=GridLayout.NEWS)

        cancel = Button(self.tk, "Cancel")
        ok = Button(self.tk, "Ok")

        self.append(cancel)
        self.append(ok)

        ok.click = self.handle_ok
        cancel.click = self.handle_cancel
        self.layout()

    def handle_ok(self, e):
        if hasattr(self, 'ok_clicked'):
            self.ok_clicked()

    def handle_cancel(self, e):
        self.close()
        self.destroy()

    def selection(self):
        return [os.path.join(self.current, f) for f in self.files.value]

class FileChooserDemo(App):
    def run(self, tk):
        self.tk = tk
        chooser = FileChooser(tk)
        chooser.open()
        ## order is relevant
        #chooser.load_directory("/Library/WebServer/Documents")
        chooser.load_directory("/home/ivo")

        def handle_ok():
            print "Select", chooser.selection()
            chooser.close()
            chooser.destroy()

        chooser.ok_clicked = handle_ok

